package com.cskaoyan.javase.practice.stage8.utils;

import com.cskaoyan.javase.practice.stage8.entity.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @program: little-practice
 * @description: create new student object by reflection method
 * @author: Keyu Li
 * @create: 2021-09-20 18:02
 **/

public class ReflectionUtils {

    private ReflectionUtils(){}

    static String studentReference = "com.cskaoyan.javase.practice.stage8.entity.Student";

    // 反射创建学生对象列表
//    public static Student[] createStudentListByReflectuon(int num)
//            throws NoSuchMethodException, ClassNotFoundException,
//            IllegalAccessException, InstantiationException,
//            InvocationTargetException {
//        if (num==0) return null;
//        Student[] stus = new Student[num];
//        for (int i = 0; i < num; i++) {
//            stus[i] = createStudentByReflectuon();
//        }
//        return stus;
//    }

    // 反射创建学生对象
    public static Student createStudentByReflectuon()
            throws ClassNotFoundException, NoSuchMethodException,
            IllegalAccessException, InvocationTargetException,
            InstantiationException {
        Class<?> stuClass = Class.forName(studentReference);
        Constructor<?> constructor = stuClass.getDeclaredConstructor();
        // 破解权限
        constructor.setAccessible(true);
        return ((Student) constructor.newInstance());
    }
}
